import 'dart:async';
import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:wk_weather/bean/EnventChangeBean.dart';
import 'package:wk_weather/bean/CityInfo.dart';


import 'package:wk_weather/utils/LocationUtil.dart';
import 'package:wk_weather/utils/NetManager.dart';
import 'package:wk_weather/utils/MyLogTool.dart';
import 'package:wk_weather/utils/SharedPreferenceTool.dart';
import 'package:wk_weather/generated/json/mybean/WeatherModel.dart';
import 'package:wk_weather/views/MyApp.dart';

part 'WeatherEvent.dart';

part 'WeatherState.dart';

class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {

  WeatherBloc( ) : super(WeatherLoading(null));

  @override
  Stream<WeatherState> mapEventToState(
    WeatherEvent event,
  ) async* {
    weatherPrint('WeatherBloc || mapEventToState event: ${event.runtimeType}');
    if (event is FetchWeatherDataEvent) {
      yield* _mapFetchWeatherToState(event.cityModel);
    }
  }

  Stream<WeatherState> _mapFetchWeatherToState(CityModel cityModel) async* {
    weatherPrint("开始请求 ${cityModel.city} 城市的数据....flag: ${cityModel.cityFlag}");
    yield WeatherLoading(cityModel);
    final resData = await NetManager.getInstance().loadWeatherData(
        LocationUtil.parseFlag(cityModel.cityFlag)[0],
        LocationUtil.parseFlag(cityModel.cityFlag)[1]);

    var allWeatherData = await SharedPreferenceTool.getAllWeatherModels();
    if (allWeatherData == null || allWeatherData.isEmpty) {
      allWeatherData = {};
    }

    if (resData == null) {
      weatherPrint("城市获取失败");
      yield WeatherFailed(cityModel);
    } else {
      // todo json字符串转对象
      var resDataStr = json.encode(resData);
      if (cityModel.isLocated == true && allWeatherData.isNotEmpty) {
        String needRemoveKey = "";
        allWeatherData.forEach((key, value) {
          if (key.contains("true")) {
            needRemoveKey = key;
            return;
          }
        });
        if (needRemoveKey != "") {
          weatherPrint('需要先移除定位城市 key: $needRemoveKey');
          allWeatherData.remove(needRemoveKey);
        }
      }
      // 如果是定位城市，需要先移除定位城市，然后在添加
      allWeatherData[ LocationUtil.convertCityFlag(cityModel.cityFlag, cityModel.isLocated) ] = resDataStr;
      await SharedPreferenceTool.saveAllWeatherModels(allWeatherData); // 新增 城市数据

      final weatherData = WeatherModelEntity().fromJson(resData);
      if (weatherData == null) {
        weatherPrint("城市获取失败");
        yield WeatherFailed(cityModel);
      } else {
        weatherPrint("城市获取成功");
        eventBus.fire(MainBgChangeEvent());
        yield WeatherSuccess(weatherData, cityModel);
      }
    }

  }
}
